var path = require('path')
var config = require('../config')
var utils = require('../config-utils/utils')
var projectRoot = path.resolve(__dirname, '../');
var env = require("dotenvr").load()
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack')
var InsertGlobalCss = require('../config-utils/webpack-insert-global-css');
var CopyWebpackPlugin = require('copy-webpack-plugin');
// var px2rem = require('postcss-pxtorem')
// var autoprefixer = require('autoprefixer')
// var babelpolyfill = require("babel-polyfill");

//Multiple Page settings
var glob = require('glob');
var entries = getEntry('./src/modules/**/*.js');

function getEntry(globPath) {
    var entries = {}, basename, tmp, pathname;
    glob.sync(globPath).forEach(function (entry) {
        basename = path.basename(entry, path.extname(entry));
        tmp = entry.split('/').splice(-3);

        if((tmp[1]+'.js')===tmp[2]){
            pathname = tmp.splice(0, 1) + '/' + basename; // 正确输出js和html的路径
            entries[pathname] = entry;
        }
    });
    console.log("base-entrys:");
    console.log(entries);
    return entries;
}

console.log("Current Env:"+env.NODE_ENV);

module.exports = {
    entry: entries,
    output: {
        path: config.build.assetsRoot,
        publicPath: env.NODE_ENV === 'production' ? config.build.cdnHost + config.build.assetsPublicPath : config.dev.assetsPublicPath,
        filename: '[name].js'
    },
    externals: {
        'jquery': "Jquery",
        'Jquery': "Jquery"
    },
    resolve: {
        extensions: ['', '.js', '.vue'],
        fallback: [path.join(__dirname, '../node_modules')],
        alias: {
            'src': path.resolve(__dirname, '../src'),
            'assets': path.resolve(__dirname, '../src/assets'),
            'components': path.resolve(__dirname, '../src/components'),
            'api': path.resolve(__dirname, '../src/api'),
            'utils': path.resolve(__dirname, '../src/utils'),
            'filters': path.resolve(__dirname, '../src/filters'),
            'locales': path.resolve(__dirname, '../src/locales'),
            'resource': path.resolve(__dirname, '../src/resource'),
        }
    },
    resolveLoader: {
        fallback: [path.join(__dirname, '../node_modules')]
    },
    module: {
        preLoaders: [
            {
                test: /\.vue$/,
                loader: 'eslint',
                include: projectRoot,
                exclude: /node_modules/
            },
            // {
            //    test: /\.js$/,
            //    loader: 'eslint',
            //    include: projectRoot,
            //    exclude: /node_modules/
            // }
        ],
        loaders: [
            {
                test: /\.vue$/,
                loader: 'vue'
            },
            {
                test: /\.js$/,
                loader: 'babel',
                include: [
                    projectRoot,
                    path.resolve('node_modules/vue-echarts'),
                    path.resolve('node_modules/resize-detector')
                ],
                exclude: /node_modules/
            },
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.obj$/,
                loader: 'file'
            },
            {
                test: /\.html$/,
                loader: 'vue-html'
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader?limit=10000&name='+utils.assetsPath('img/[name].[hash:7].[ext]')
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url',
                query: {
                  limit: 10000,
                  name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
                }
            },
            {
                test: /vue-preview.src.*?js$/,
                loader: 'babel'
            },
            //解析.scss文件,对于用 import 或 require 引入的sass文件进行加载，以及<style lang="sass">...</style>声明的内部样式进行加载
            // {
            //     test: /\.scss$/,
            //     //这里用了样式分离出来的插件，如果不想分离出来，可以直接这样写 loader:'style!css!sass'
            //     loader: ExtractTextPlugin.extract('style', 'css!postcss!sass')
            // }
        ]
    },
    eslint: {
        formatter: require('eslint-friendly-formatter')
    },
    vue: {
        loaders: utils.cssLoaders()
        // postcss: [
        //     require('autoprefixer')({ browsers: ['last 10 Chrome versions', 'last 5 Firefox versions', 'Safari >= 6', 'ie > 8'] })
        // ]    
    },
    //公共的module模版
    common_modules: {
        header_metadata: path.resolve(__dirname, '../src/common_html/header_metadata.html')
    },
    plugins: [
        new InsertGlobalCss(glob.sync('./src/common_css/*.css')),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"'+env.NODE_ENV+'"'
            }
        }),
        new CopyWebpackPlugin([
            // Copy glob results (with dot files) to /absolute/path/
            {
                from: path.resolve(__dirname, '../public'),
                to: path.resolve(__dirname, '../dist/public'),
                force: true   //强行覆盖原有内容
            },
        ], {
            ignore: [],
            copyUnmodified: true,
            debug:"debug"
        })
    ]
}

//加载第三方类库
var libs = getLibs('./src/common_js/*.js');
function getLibs(globPath) {
    var entries = {}, basename, tmp, pathname, names = [];

    var entries = glob.sync(globPath), newEntries = [];
    //把jquery放在最前
    entries.forEach(function (v, k){
        if(v.indexOf('jquery') === -1){
            newEntries.push(v);
            entries.splice(k, 1);
        }
    });
    newEntries.concat(entries).forEach(function (entry) {
        basename = path.basename(entry, path.extname(entry));
        module.exports.entry[basename] = entry;
        names.push(basename);
    });
    module.exports.libNames = names;
    module.exports.plugins.push(new webpack.optimize.CommonsChunkPlugin({
        names: names
    }));
    
    return entries;
}
